package dtu.app.listadapter;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.iqengines.demo.R;
import com.iqengines.sdk.Utils;

import dtu.app.model.Product;

public class ProductArrayAdapter extends ArrayAdapter<Product> {

	private final LayoutInflater mInflater;
	
	public ProductArrayAdapter(Context context) {
		super(context, android.R.layout.simple_list_item_2);
		mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}
	
	public void setData(List<Product> data) {
		clear();
		if (data != null) {
			for (Product p : data) {
				add(p);
			}
		}
	}
	
    /**
     * Populate new items in the list.
     */
    @Override public View getView(int position, View convertView, ViewGroup parent) {
        View view;
 
        if (convertView == null) {
            view = mInflater.inflate(R.layout.product_item, parent, false);
        } else {
            view = convertView;
        }
        
        Product item = getItem(position);
        ((TextView)view.findViewById(R.id.product_name)).setText(item.getName());
        ((TextView)view.findViewById(R.id.product_total)).setText(Double.toString(item.getInStock()));
        
        Log.i("IMAGE PATH", item.getImagePath());
        
        InputStream is = null;
		try {
			is = getContext().getAssets().open(item.getImagePath());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}				
		Bitmap origBmp = BitmapFactory.decodeStream(is);
//		Bitmap thumb = transformBitmapToThumb(origBmp);
        
//        ((ImageView)view.findViewById(R.id.product_image)).setImageBitmap(thumb);
 
        return view;
    }
    
	private Bitmap transformBitmapToThumb(Bitmap origBmp) {
		int thumbSize = getContext().getResources().getDimensionPixelSize(R.dimen.thumb_size);
		return Utils.cropBitmap(origBmp, thumbSize);
	}

}
